package dnacos

import (
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
)

//type INacosConfigClient[T any] interface {
//	ReadConfigFromYml[T any](dataId string, group string, config T) T //读取配置文件,返回给定的对象类型
//}

type NacosConfigClient[T any] struct {
	client        config_client.IConfigClient
	serviceClient naming_client.INamingClient
}

//var x INacosConfigClient = NacosConfigClient{}

func NewNacosConfigClient[T any](ip string, port uint64, NamespaceId string, level string) NacosConfigClient[T] {
	//wd, err := os.Getwd()
	//if err != nil {
	//	panic(any(err))
	//}

	serverConfig := []constant.ServerConfig{
		{
			IpAddr: ip,   //nacos 地址
			Port:   port, //nacos 端口
		},
	}

	clientConfig := &constant.ClientConfig{
		NamespaceId:         NamespaceId, //命名空间 比较重要 拿取刚才创建的命名空间ID
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/logs/nacos",
		CacheDir:            "/tmp/cache/nacos",
		LogLevel:            level,
	}

	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  clientConfig,
			ServerConfigs: serverConfig,
		},
	)

	if err != nil {
		return NacosConfigClient[T]{}
	}

	serviceClient, err := clients.NewNamingClient(
		vo.NacosClientParam{
			ClientConfig:  clientConfig,
			ServerConfigs: serverConfig,
		})

	if err != nil {
		return NacosConfigClient[T]{}
	}
	if err != nil {
		//读取配置文件失败
		panic(any(err))
	}
	return NacosConfigClient[T]{client: configClient, serviceClient: serviceClient}
}
